package com.qfmy.web.app.service.impl.user;

import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.user.Address;
import com.qfmy.web.app.mapper.user.AddressMapper;
import com.qfmy.web.app.service.agent.ChatService;
import com.qfmy.web.app.service.user.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.user
 * @date 2025/9/17
 * @description 地址
 */
@Service
public class AddressServiceImpl implements AddressService {

    /**
     * 注入mapper
     */
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 注入chatService
     */
    @Autowired
    private ChatService chatService;

    /**
     * 添加地址
     * @param address
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAddress(String address) {
        //获取当前用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        Long userId = loginUser.getUserId();
        //分割地址
        String[] addressArray = address.split(",");
        //获取省市区
        String province = addressArray[0];
        String city = addressArray[1];
        String district = addressArray[2];
        //调用大模型获取行政编码
        String content = "请根据" + district + "获取该地区的行政编码只要回答行政编码就行其他的不需要";
        String code = chatService.service(content);
        //创建地址对象
        Address ad = new Address();
        ad.setProvince( province);
        ad.setCity(city);
        ad.setDistrict(district);
        ad.setZipCode(code);
       ad.setUserId(userId);
       //插入数据库
        addressMapper.insert(ad);
    }

    /**
     * 判断用户是否添加过地址
     * @return
     */
    @Override
    public Boolean isAddAddress() {
        //获取当前用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        Long userId = loginUser.getUserId();
        //判断用户是否添加过地址
        return addressMapper.isAddAddress(userId);
    }
}
